package com.itheima.poi_test;

import java.io.InputStream;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * 自定义Excel解析器
 * Excel百万数据读取
 */
public class ExcelParser {

    public void parse(String path) throws Exception{
        //1.根据Excel获取OPCPackage对象
        OPCPackage opcPackage = OPCPackage.open(path);
        //2.创建XSSFReader对象
        XSSFReader reader = new XSSFReader(opcPackage);
        //3.获取SharedStringsTable对象
        SharedStringsTable sst = reader.getSharedStringsTable();
        //4.获取StylesTable对象
        StylesTable stylesTable = reader.getStylesTable();
        //5.创建Sax的XmlReader对象
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        //6.设置处理器
        XSSFSheetXMLHandler xmlHandler = new XSSFSheetXMLHandler(stylesTable, sst, new SheetHandler(), false);
        xmlReader.setContentHandler(xmlHandler);
        XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator)reader.getSheetsData();
        //7.逐行读取
        while (sheets.hasNext()) {
            // 每一个sheet页的流信息
            InputStream sheetstream = sheets.next();
            InputSource sheetSource = new InputSource(sheetstream);
            xmlReader.parse(sheetSource);
            sheetstream.close();
            opcPackage.close();
        }
    }
}
